package com.example.hao.musicplayer.service;

import android.app.Service;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

import com.example.hao.musicplayer.MainActivity;

public class MusicService extends Service {


    private static final String TAG = "MusicService";
    private MediaPlayer mediaPlayer;

    public MusicService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "onBind: ");
        return new MyBind();
    }

    private MainActivity.OnProgressCallBack progressCallBack;

    public class MyBind extends Binder {


        public void playMusic() {
            startPlay();
        }

        public void pause() {
            pauseMusic();
        }

        public void nextSong() {
            playNext();
        }

        public void seekTo(int progress) {
            if (mediaPlayer != null)
                mediaPlayer.seekTo((int) (progress / 100.0 * mediaPlayer.getDuration()));

        }

        public void setProgressCallBack(MainActivity.OnProgressCallBack progressCallBack) {
            MusicService.this.progressCallBack = progressCallBack;
        }
    }


    @Override
    public void unbindService(ServiceConnection conn) {
        super.unbindService(conn);
        Log.d(TAG, "unbindService: ");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate: ");
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if (mediaPlayer != null) {
                        int duration = mediaPlayer.getDuration();
                        int currentPosition = mediaPlayer.getCurrentPosition();
                        progressCallBack.onProgress((int) (100.0 * currentPosition / duration));
                    }
                }
            }
        }).start();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand: ");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "onDestroy: ");
    }

    private void startPlay() {
        if (mediaPlayer == null)
            new Thread(new Runnable() {
                @Override
                public void run() {
                    mediaPlayer = MediaPlayer.create(MusicService.this, Uri.parse("http://96.ierge.cn/11/168/336613.mp3"));
                    mediaPlayer.start();
                }
            }).start();
    }

    private void pauseMusic() {
        if (mediaPlayer != null)
            mediaPlayer.pause();
    }

    private void playNext() {
        Log.w(TAG, "nextSong: 下一首歌...");
    }


}
